package com.dr.web.controllers;

import com.dr.common.pojo.WeChatFinalValue;
import com.dr.common.pojo.WeChatOpenid;
import com.dr.common.ution.DateUtil;
import com.dr.common.ution.StringUtil;
import com.dr.common.ution.WeChatUtil;
import com.dr.exception.ServiceExcep;
import com.dr.pojo.Location;
import com.dr.pojo.Student;
import com.dr.pojo.WeChatUserInfo;
import com.dr.service.LocationService;
import com.dr.service.StudentInfoService;
import com.dr.service.WeChatUserInfoService;
import org.apache.ibatis.logging.Log;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by tugou on 2017/4/25.
 * 报名界面controller
 */
@Controller
@RequestMapping("student")
public class SignUpController {

    @Autowired
    StudentInfoService studentInfoService;
    @Autowired
    LocationService locationService;
    @Autowired
    WeChatUserInfoService weChatUserInfoService;


    static Logger logger =  Logger.getLogger(SignUpController.class);
    /**
     * 微信报名页面
     * @param session
     * @param code
     * @return
     */
    @RequestMapping(value="sign",method= RequestMethod.GET)
    public String signUp(HttpSession session, String code,Model model){
        if (StringUtil.isNotEmpty(code)){
            WeChatOpenid content =  WeChatUtil.getWeChatOpenid(code);
            String openId = content.getOpenid();
            WebchatInfSave webchatInfSave = new WebchatInfSave(content);//实例化内部类，保存微信用户访问信息
            Thread thread = new Thread(webchatInfSave);
            thread.start();//启动线程保存微信用户信息
            logger.info("获取Openid："+openId+"||"+ new Date());
            session.setAttribute("openId",openId);
            Student student = studentInfoService.getStudent(openId);
            if (student == null){
                return "/wechat/register";
            }
            if (student.getBespeak() == 1){
                model.addAttribute("student",student);
                return "/wechat/bookIng";
            }
            if (student.getBespeak() == 2){
                Location loc = locationService.getLocationById(String.valueOf(student.getLocationId()));
                model.addAttribute("loc",loc);
                return "/wechat/complete";
            }
        }
        else{
            return "redirect:"+ WeChatFinalValue.WECHAT_MAIN;
        }
        return null;
    }

    /**
     * 驾校列表
     * @return
     */
    @RequestMapping(value="schoolListPage",method= RequestMethod.GET)
    public String schoolListPage(Model model){
        Location location = new Location();
        location.setState(1);
        List<Location> list = locationService.getAllLocation(location);
        model.addAttribute("locationList",list);
        return "/wechat/schoolList";
    }

    /**
     * 学员登记注册
     * @return
     */
    @RequestMapping(value = "signIn",method= RequestMethod.POST)
    public String signIn(HttpSession session, Student student, Model model){
        String openId = (String) session.getAttribute("openId");
        student.setOpenId(openId);
        try {
            //WeChatUtil.weChatFileUpLoad(student.getCertificatesA(),openId+"A.jpg");
            //WeChatUtil.weChatFileUpLoad(student.getCertificatesB(),openId+"B.jpg");
            //student.setCertificatesA(openId+"A.jpg");
            //student.setCertificatesB(openId+"B.jpg");
            studentInfoService.saveStudent(student);
            session.setAttribute("student",student);
        } catch (ServiceExcep excep) {
            excep.printStackTrace();
        }
        return "/wechat/bookIng";
    }

    @RequestMapping(value = "bespeakSchool/{locationId}",method= RequestMethod.GET)
    public String bespeakSchool(HttpSession session,@PathVariable int locationId,Model model){
        String openId = (String) session.getAttribute("openId");
        Student student = studentInfoService.getStudent(openId);
        student.setBespeak(2);
        student.setLocationId(locationId);
        try {
            Location loc = locationService.getLocationById(String.valueOf(locationId));
            studentInfoService.updateStudent(student);
            model.addAttribute("loc",loc);
        } catch (ServiceExcep excep) {
            excep.printStackTrace();
        }
        return "/wechat/complete";
    }

    public String filterEmoji(String source) {
        if(source != null)
        {
            Pattern emoji = Pattern.compile ("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",Pattern.UNICODE_CASE | Pattern . CASE_INSENSITIVE ) ;
            Matcher emojiMatcher = emoji.matcher(source);
            if ( emojiMatcher.find())
            {
                source = emojiMatcher.replaceAll("*");
                return source ;
            }
            return source;
        }
        return source;
    }


    class WebchatInfSave implements Runnable{

        private WeChatOpenid openId;

        WebchatInfSave(WeChatOpenid _openId){
            openId = _openId;
        }
        @Override
        public void run() {
            WeChatUserInfo info = WeChatUtil.getWeChatUserInfoByOpenId(openId);
            WeChatUserInfo par = new WeChatUserInfo();
            par.setOpenid(info.getOpenid());
            try {
                WeChatUserInfo userInfo = weChatUserInfoService.getWeChatUserInfo(par);
            } catch (ServiceExcep excep) {
                try {
                    info.setNickname(filterEmoji(info.getNickname()));
                    weChatUserInfoService.saveWeChatUserInfo(info);
                } catch (ServiceExcep excep1) {
                    excep1.printStackTrace();
                }
            }
        }
    }
}
